import { JosnType, ToClassOptions } from "./typing";
import { isArray, setKeyNotNull, setInterfaceModel, firstLetterCap, stripIndent, isObjectOrArray, isNull, setDefaultNull, setDefaultNeedPropertyValue, isObject } from "./utils";
let TextResult: string = ""

export const toClass = (className: string = "JsonToClass", rawJson: JosnType | string, options: ToClassOptions = {}, repeat: boolean = false): string => {
  typeof(rawJson) === "string" ? rawJson = JSON.parse(rawJson) : null;
  isArray(rawJson) ? rawJson = rawJson[0] : null

  if (!repeat) {
    TextResult = ""
  }

  let classText: string = stripIndent `
    ${setInterfaceModel(options)} ${className} {
      ${
        Object.keys(rawJson).map(key => {
          let ArrayInsideNotObject = false
          
          if(isObjectOrArray(rawJson[key]))  {
            // 如果第一层key是数组，且 数组内 套的 是对象
            if (isArray(rawJson[key]) && isObject(rawJson[key][0])) {
              toClass(firstLetterCap(key) ,rawJson[key], options, true)
            }

            // 如果是对象
            if (isObject(rawJson[key])) {
              ArrayInsideNotObject = false
              toClass(firstLetterCap(key) ,rawJson[key], options, true)
            } 
          }

          return `${setDefaultNeedPropertyValue(options,key) == null ? '' : setDefaultNeedPropertyValue(options,key) }
            ${setKeyNotNull(options,key)}: ${ 
              ArrayInsideNotObject 
              ? `${typeof rawJson[key][0]}[]`
              : isObjectOrArray(rawJson[key]) 
                ? `${firstLetterCap(key)}${isArray(rawJson[key]) ? '[]' : ''}` 
                : isNull(rawJson[key]) ? setDefaultNull(options) : typeof rawJson[key]
            };
          `
        })
      }
    }
  `;

  TextResult += `${classText} \n\n`
  return TextResult
}
